#include "../DWMRICore/HOT.h"
#include "../DWMRICore/Fiber.h"
#include "../DWMRICore/Scalar.h"

#include <vector>

using namespace std;

char *pSrcPathname = NULL;

float offsetX = 113;
float offsetY = 149;
float offsetZ = 0;

int FindOffset(FILE *fp)
{
	char buffer[256];
	do {
		fscanf(fp, "%s", buffer);
	} while (strcmp(buffer, "file:") != 0);

	fscanf(fp, "%s", buffer);
	
	int offset;
	fscanf(fp, "%d", &offset);

	return offset;
}

int FindFiberCount(FILE *fp)
{
	char buffer[256];
	do {
		fscanf(fp, "%s", buffer);
	} while (strcmp(buffer, "count:") != 0);

	int count = 0;
	fscanf(fp, "%d", &count);

	return count;
}

int main(int argc, char *argv[])
{
	pSrcPathname	   =			"C:\\Ziang\\Dataset\\HumanConnectome\\792564_processed\\For_Paper\\B3000\\Probabilistic_Fibers\\100K\\fibers_100K_00.tck";
	char *confPathname = "C:\\Ziang\\Dataset\\HumanConnectome\\792564_processed\\For_Paper\\B3000\\Probabilistic_Fibers\\converted\\fibers_1M_39.conf";
	char *vertPathname = "C:\\Ziang\\Dataset\\HumanConnectome\\792564_processed\\For_Paper\\B3000\\Probabilistic_Fibers\\converted\\fibers_1M_39.vert";

	FILE *fp = fopen(pSrcPathname, "rb");
	if (NULL == fp)
		return false;

	/* find the offset of the binary data */
	int offset = FindOffset(fp);
	
	/* find the fiber count */
	fseek(fp, 0, SEEK_SET);
	int fiberCount = FindFiberCount(fp);

	CFiber *pFibers = new CFiber[fiberCount];
	
	/* read binary data */
	if (fseek(fp, offset, SEEK_SET) == 0) {
		for (int i = 0; i < fiberCount; ++i) {
			vector<CPoint3F> ptVec;
			float p[3];
			while(true) {
				fread(p, sizeof(float), 3, fp);
				if (p[0] != p[0])
					break;
				CPoint3F pt(p[0]+offsetX, p[1]+offsetY, p[2]+offsetZ);
				ptVec.push_back(pt);
			}

			/* convert fiber */
			uint fCount = ptVec.size() / 2;
			uint bCount = ptVec.size() - fCount + 1;
			CPoint3F *pF = new CPoint3F[fCount];
			CPoint3F *pB = new CPoint3F[bCount];
			for (uint j = 0; j < fCount; ++j) {
				pF[j] = ptVec.at(fCount-j-1);
			}
			for (uint j = 0; j < bCount; ++j) {
				pB[j] = ptVec.at(j+fCount-1);
			}

			Seed seed;
			seed.pos = pF[0];
			seed.dir = pF[1] - pF[0];
			seed.dir.Normalize();
			pFibers[i].CreateFiber(pF, pB, fCount, bCount, &seed);

			SafeDeleteArray(pF);
			SafeDeleteArray(pB);
		}
		
	}

	fclose(fp);

	/* save converted fibers */

	SaveFibers(confPathname, vertPathname, pFibers, fiberCount, 1);
	
	SafeDeleteArray(pFibers);
}